package com.frank.libandroid.util;

import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class RadioGroupUtil {
    public static String getCheckedString(RadioGroup group) {
        for (int i = 0; i < group.getChildCount(); i++) {
            if (group.getChildAt(i) instanceof TextView) {
                TextView childAt = (TextView) group.getChildAt(i);
                if (childAt.getId() == group.getCheckedRadioButtonId()) {
                    return childAt.getText().toString();
                }
            }
        }
        return null;
    }

    public static void check(RadioGroup group, String text) {
        for (int i = 0; i < group.getChildCount(); i++) {
            if (group.getChildAt(i) instanceof TextView) {
                TextView childAt = (TextView) group.getChildAt(i);
                if (childAt.getText().toString().equals(text)) {
                    group.check(childAt.getId());
                    break;
                }
            }
        }
    }

    public static int getCheckedIndex(RadioGroup radioGroup) {
        int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
        int index = 0;
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            View childAt = radioGroup.getChildAt(i);
            if (checkedRadioButtonId == childAt.getId()) {
                return index;
            }
            if (childAt instanceof RadioButton) {
                index++;
            }
        }
        return -1;
    }

    public static void checkIndex(RadioGroup group, int sortType) {
        if (sortType < 0 || sortType >= group.getChildCount()) {
            return;
        }
        int index = 0;
        for (int i = 0; i < group.getChildCount(); i++) {
            View childAt = group.getChildAt(i);
            if (childAt instanceof RadioButton) {
                RadioButton button = (RadioButton) childAt;
                if (sortType == index) {
                    button.setChecked(true);
                    break;
                }
                index++;
            }
        }
    }

    public interface OnCheckIndexChange {
        void onCheckIndexChange(int index);
    }

    public static void setOnCheckIndexChange(RadioGroup radioGroup, OnCheckIndexChange tipStatus) {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int checkedIndex = getCheckedIndex(radioGroup);
                tipStatus.onCheckIndexChange(checkedIndex);
            }
        });
    }
}
